package analysis;

import common.AnalysisWare;
import common.Constants;
import common.DataAnalysis;
import util.FileUtil;
import util.remote.RemoteConnectResult;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by J.Chen on 2017/5/27.
 */

@AnalysisWare(confCode = "ACT_2017_02_NEW_PLAYER_SFLC", desc = "首付累充")
public class NewPlayerSflcAnalysis extends DataAnalysis {
    public NewPlayerSflcAnalysis(RemoteConnectResult result, String confCode) {
        super(result, confCode);
    }

    @Override
    public void execute() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(actConf.getTimeStart());
        String key0 = signHandleKey(calendar, 0);
        FileUtil fileUtil0 = new FileUtil(Constants.getActOutputDir(result.getRemoteConf(), actConf.getConfCode(), "首付"));
        ex(key0, fileUtil0);
        String key1 = signHandleKey(calendar, 1);
        FileUtil fileUtil1 = new FileUtil(Constants.getActOutputDir(result.getRemoteConf(), actConf.getConfCode(), "累充"));
        ex(key1, fileUtil1);

        for (; calendar.before(Calendar.getInstance()); calendar.add(Calendar.MONTH, 1)) {
            String key2 = signHandleKey(calendar, 2);
            FileUtil fileUtil2 = new FileUtil(Constants.getActOutputDir(result.getRemoteConf(), actConf.getConfCode(), "月首付", "" + (calendar.get(Calendar.MONTH) + 1)));
            ex(key2, fileUtil2);
        }

    }

    public void ex(String key, FileUtil fileUtil) {
        Map<String, String> map = result.getRedisUtil().hgetAll(key);
        Map<String, Integer> result = new HashMap<>();
        for (String value : map.keySet()) {
            String[] s = value.split(":", 2);
            if (result.containsKey(s[1])) {
                result.put(s[1], result.get(s[1]) + 1);
            } else {
                result.put(s[1], 1);
            }
        }
        for (Map.Entry<String, Integer> en : result.entrySet()) {
            fileUtil.writeln("|", en.getKey(), "" + en.getValue());
        }
        fileUtil.close();
    }

    public String signHandleKey(Calendar calendar, int type) {
        String key = String.join(":", "hAct", "sflc", "signHandle", "" + type);
        if (type == 2) {
            Calendar cal = calendar;
            key = String.join(":", key, "" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH));
        }
        return key;
    }

}
